import { Effect, ImmerReducer, Subscription, history } from 'umi';
import { query } from './service';

export interface PageAllModelState {
  data: any | undefined;
}

export interface LastingIpModelType {
  namespace: 'pageAll';
  state: PageAllModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    // 启用 immer 之后
    querySuccess: ImmerReducer<PageAllModelState>;
  };
  subscriptions: { setup: Subscription };
}

const LastingIpModel: LastingIpModelType = {
  namespace: 'pageAll',

  state: {
    data: undefined,
  },

  effects: {
    *query({}, { call, select, put }) {
      const report_id = history.location.query.report_id;
      const response = yield call(query, { report_id });
      if (response && response.code === 200) {
        yield put({
          type: 'querySuccess',
          payload: {
            data: response.data,
          },
        });
      }
    },
  },
  reducers: {
    // 启用 immer 之后
    querySuccess(state, { payload }) {
      const { data } = payload;
      return {
        ...state,
        data,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(async ({ pathname }) => {
        if (pathname === '/pageall') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default LastingIpModel;
